package com.zmn.oms.services.config;

import com.alibaba.fastjson.JSON;
import com.zmn.oms.model.entity.chan.FacadeMessageDoc;
import com.zmn.oms.model.entity.log.FacadeTrackLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.index.IndexResolver;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import java.util.List;
import java.util.Optional;

/**
 * 类描述：自动创建 mongoDB 数据库索引
 *
 * @author lhl
 * @date 2021/01/07 15:27
 */
@Slf4j
@Configuration
public class OmsMongoDBAutoIndexConfig {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoConverter mongoConverter;


    @EventListener(ApplicationReadyEvent.class)
    public void initIndicesAfterStartup() {
        log.info("=========================== MongoDB 自动创建索引 ===========================");
        MongoMappingContext mongoMappingContext = Optional.ofNullable(this.mongoConverter.getMappingContext())
                .map(context -> context instanceof MongoMappingContext ? (MongoMappingContext)context : null)
                .orElse(null);
        if (mongoMappingContext == null) {
            return;
        }

        IndexResolver resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);
        IndexOperations indexOps = null;
        List<IndexInfo> indexInfo = null;

        // FacadeMessage
        indexOps = mongoTemplate.indexOps(FacadeMessageDoc.class);
        resolver.resolveIndexFor(FacadeMessageDoc.class).forEach(indexOps::ensureIndex);
        indexInfo = indexOps.getIndexInfo();
        log.info("MongoDB: FacadeMessageDoc: [{}]", JSON.toJSONString(indexInfo));

        // FacadeTrackLog
        indexOps = mongoTemplate.indexOps(FacadeTrackLog.class);
        resolver.resolveIndexFor(FacadeTrackLog.class).forEach(indexOps::ensureIndex);
        indexInfo = indexOps.getIndexInfo();
        log.info("MongoDB: FacadeTrackLog: [{}]", JSON.toJSONString(indexInfo));
    }
}
